//
//  DEWSmallBusinessViewController.m
//  OtherDemo
//
//  Created by lianjie on 2018/7/28.
//  Copyright © 2018年 lianjie. All rights reserved.
//
////____________邻里微商___________

#import "DEWSmallBusinessViewController.h"
#import "HWTextView.h"
#import "ACSelectMediaView.h"


@interface DEWSmallBusinessViewController ()<UITextFieldDelegate,UITextViewDelegate>

@property (nonatomic ,strong) UIScrollView *scrollView;

///标题
@property (nonatomic ,strong) CMInputView *titleTextView;;
///价格
@property (nonatomic ,strong) UITextField *priceTextField;
///内容
@property (nonatomic ,strong) CMInputView *descTextView;
///图片
@property (nonatomic ,strong) ACSelectMediaView *mediaView;

///上传的照片
@property (nonatomic ,strong) NSMutableArray *photos;

///发布
@property (nonatomic ,strong) UIButton *sendBtn;

@end

@implementation DEWSmallBusinessViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"邻里微商";
    
    [self createView];
    [self setupNavItem];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [_titleTextView becomeFirstResponder];
}

#pragma mark ---发布信息
- (void)sendInfoAction
{
    
    
    NSMutableArray *imageArr = [NSMutableArray array];
    [self.photos enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        ACMediaModel *model = obj;
        
        [imageArr addObject:model.image];
        
    }];
    
    NSMutableDictionary *paramDic = [NSMutableDictionary dictionary];
    DELoginModel *model = [HHUserManager getUserInfo];

    paramDic[@"userId"] = model.userId;
    paramDic[@"tokenId"] = model.tokenId;
    paramDic[@"estateId"] = model.attestation[@"estateId"];
    
    paramDic[@"title"] = _titleTextView.text;
    paramDic[@"price"] = _priceTextField.text;
    paramDic[@"text"] = _descTextView.text;
    
     NSMutableArray *qualifiMarray = [NSMutableArray arrayWithCapacity:0];
     for (int i = 0; i < imageArr.count; i++) {
     NSData *imageData;
     if ([imageArr[i] class] == [UIImage class]) {
         imageData = UIImageJPEGRepresentation(imageArr[i], 1.0);
     }else{
         imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString appendImageString:imageArr[i]]]];
         
     }
     NSString *pictureStr = [imageData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
     
     NSDictionary *dict = @{@"imagetype":@"png",@"image":pictureStr};
     [qualifiMarray addObject:dict];
     }
     NSString *pictureStr = [StringHelper jsonStringFromObject:qualifiMarray];
     paramDic[@"businessPicList"] = pictureStr;
    [self showIndicatorHint:@"正在上传单据图片..."];
//        [MBProgressHUD showMessage:@"正在上传单据图片..."];
    weakSelf(weakSelf);
     [KSHTTPSTool post:[KSService sendGoodGoods] params:paramDic formData:nil progress:^(NSProgress *downloadProgress) {
     } success:^(id responseObject) {
         
         [weakSelf hideHud:YES];
         NSLog(@"%@",responseObject);
         
//         [MBProgressHUD hideHUD];
     if (DERetCode) {
         [weakSelf showHint:responseObject[@"retMsg"]];
         dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
         [weakSelf.navigationController popViewControllerAnimated:YES];
         });
     }else{
         [[AlertHelper sharedManager] alertWithMessage:responseObject[@"retMsg"]];
     }
     } failure:^(NSError *error) {
//         [MBProgressHUD hideHUD];
         [weakSelf showHint:@"服务中断,请稍后..."];
         [weakSelf hideHud:YES];
     }];
    
    
}

#pragma mark ----初始化视图
///设置导航按钮
- (void) setupNavItem
{
    _sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _sendBtn.frame = CGRectMake(0, 0, 60, 25);
    [_sendBtn addTarget:self action:@selector(sendInfoAction) forControlEvents:UIControlEventTouchUpInside];
    _sendBtn.titleLabel.font = [UIFont systemFontOfSize:13.0f];
    _sendBtn.layer.masksToBounds = YES;
    _sendBtn.layer.cornerRadius = 4.0f;
    _sendBtn.layer.borderWidth = 1.0f;
    [_sendBtn setTitle:@"发布" forState:UIControlStateNormal];
    [self setSendBtnView:NO];
    UIBarButtonItem *item = [[UIBarButtonItem alloc]initWithCustomView:_sendBtn];
    self.navigationItem.rightBarButtonItem = item;
    
}
///设置导航按钮
- (void) setSendBtnView:(BOOL)isEdit
{
    if (isEdit) {
        _sendBtn.userInteractionEnabled = YES;
        _sendBtn.backgroundColor = UIColorFromRGB(0xFF8900);
        _sendBtn.layer.borderColor = UIColorFromRGB(0xFF8900).CGColor;
        [_sendBtn setTitleColor:WhiteColor forState:UIControlStateNormal];
    }else{
        _sendBtn.userInteractionEnabled = NO;
        _sendBtn.backgroundColor = WhiteColor;
        _sendBtn.layer.borderColor = UIColorFromRGB(0xDCDCDC).CGColor;
        [_sendBtn setTitleColor:UIColorFromRGB(0xBCBCBC) forState:UIControlStateNormal];
    }
    
}
///判断发布按钮是否能编辑
- (void)sendBtnIsAbleEdit
{
    if (![BaseUtils isBlankString:_titleTextView.text] && ![BaseUtils isBlankString:_priceTextField.text] && ![BaseUtils isBlankString:_descTextView.text]) {
        [self setSendBtnView:YES];
    }else{
        [self setSendBtnView:NO];
    }
    
}


///绘制页面
-(void)createView
{
    ///底部
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, DEWScreenWidth, DEWScreenHeight-NAVH)];
    _scrollView.backgroundColor = BGVColor;
    
    [self.view addSubview:_scrollView];
    
    UIView *topBgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DEWScreenWidth, 60.0f)];
    topBgView.backgroundColor = WhiteColor;
    [self.scrollView addSubview:topBgView];
    
    ///
    _titleTextView = [[CMInputView alloc]init];
    _titleTextView.frame = CGRectMake(Margin_15, 15, DEWScreenWidth-Margin_15*2, 30.0f);
    _titleTextView.placeholder = @"物品名称（8-25字）";
    _titleTextView.placeholderColor = UIColorFromRGB(0xBCBCBC);
    _titleTextView.placeholderFont = [UIFont systemFontOfSize:18.0f weight:UIFontWeightHeavy];
    _titleTextView.backgroundColor = WhiteColor;
    _titleTextView.tintColor = UIColorFromRGB(0xFF8900);
    _titleTextView.font = [UIFont systemFontOfSize:18.0f weight:UIFontWeightHeavy];
    _titleTextView.maxNumberOfLines = 2;
    weakSelf(weakSelf);
    
    [topBgView addSubview:_titleTextView];
    
    
    
    
    ///价格
    UIView *priceBgView = [[UIView alloc]init];
    priceBgView.backgroundColor = WhiteColor;

    priceBgView.frame = CGRectMake(0, topBgView.Wbotoom+10, DEWScreenWidth, 50.0f);
    [self.scrollView addSubview:priceBgView];
    
    ///必填
    UILabel *signLab = [[UILabel alloc]initWithFrame:CGRectMake(Margin_15, 18, 30, 15)];
    signLab.text = @"必填";
    signLab.textColor = UIColorFromRGB(0xFF8900);
    signLab.textAlignment = NSTextAlignmentCenter;
    signLab.layer.masksToBounds = YES;
    signLab.layer.borderColor = UIColorFromRGB(0xFF8900).CGColor;
    signLab.layer.borderWidth = 1.0f;
    signLab.font = [UIFont systemFontOfSize:11];
    [priceBgView addSubview:signLab];
    
    UILabel *titLab = [[UILabel alloc]init];
    titLab.text = @"价格";
    titLab.font = [UIFont systemFontOfSize:16.0f];
    titLab.layer.cornerRadius = 4.0f;
    titLab.layer.masksToBounds = YES;
    titLab.textColor = Color_33;
    titLab.frame = CGRectMake(signLab.right+10, 14, 40, 23);
    [priceBgView addSubview:titLab];
    
    ///价格
    UITextField *priceTextFiled = [[UITextField alloc]init];
    priceTextFiled.keyboardType = UIKeyboardTypeDecimalPad;
    priceTextFiled.textColor = Color_33;
    priceTextFiled.frame = CGRectMake(DEWScreenWidth-180-Margin_15, 14, 180, 23);
    priceTextFiled.tintColor = UIColorFromRGB(0xFF8900);
    _priceTextField = priceTextFiled;
    priceTextFiled.textAlignment = NSTextAlignmentRight;
    priceTextFiled.placeholder = @"请输入物品价格";
    [priceBgView addSubview:priceTextFiled];
    [priceTextFiled addTarget:self action:@selector(textfieldTextDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    UIView *bottomView = [[UIView alloc]initWithFrame:CGRectMake(0,priceBgView.Wbotoom+Margin_10, DEWScreenWidth, 120)];
    bottomView.backgroundColor = WhiteColor;

    
    [self.scrollView addSubview:bottomView];
    
    ///内容
    _descTextView = [[CMInputView alloc]initWithFrame:CGRectMake(Margin_15,0, DEWScreenWidth-Margin_15*2, 60)];
    _descTextView.textColor = Color_33;
    _descTextView.placeholderColor = Color_99;
    _descTextView.placeholder = @"输入您想推送的内容";
    _descTextView.placeholderFont = [UIFont systemFontOfSize:16];
    _descTextView.font = [UIFont systemFontOfSize:16];
    _descTextView.maxNumberOfLines = 6;
    _descTextView.tintColor = UIColorFromRGB(0xFF8900);
    [bottomView addSubview:_descTextView];
    
    _titleTextView.textChangedBlock = ^(NSString *text, CGFloat textHeight) {
        
        CGRect frame = weakSelf.titleTextView.frame;
        frame.size.height = textHeight;
        weakSelf.titleTextView.frame = frame;
        if (textHeight+30>60) {
            topBgView.height = textHeight+30;
        }else{
            topBgView.height = 60.0f;
        }
        
        priceBgView.y = topBgView.Wbotoom+10;
        bottomView.y = priceBgView.Wbotoom+10;
        weakSelf.mediaView.y = bottomView.Wbotoom;
        
    };
    
    _descTextView.textChangedBlock = ^(NSString *text, CGFloat textHeight) {
        if (textHeight>60) {
            CGRect frame = weakSelf.descTextView.frame;
            frame.size.height = textHeight;
            weakSelf.descTextView.frame = frame;
            
            
        }else{
            weakSelf.descTextView.height = 60;
        }
        
        if (textHeight>120) {
            bottomView.height = textHeight;
        }else{
            bottomView.height = 120.0f;
        }
        weakSelf.mediaView.y = bottomView.Wbotoom;
//        [weakSelf sendBtnIsAbleEdit];
    };
    _titleTextView.textBlcok = ^(NSString *text) {
      [weakSelf sendBtnIsAbleEdit];
    };
    _descTextView.textBlcok = ^(NSString *text) {
      [weakSelf sendBtnIsAbleEdit];
    };
    
    ACSelectMediaView *mediaView = [[ACSelectMediaView alloc] initWithFrame:CGRectMake(0, bottomView.Wbotoom, DEWScreenWidth, 1)];
    mediaView.type = ACMediaTypeAll;
    mediaView.maxImageSelected = 6;
    mediaView.naviBarBgColor = WhiteColor;
    mediaView.naviBarTitleColor = NavRed;
    mediaView.rowImageCount = 3;
    mediaView.lineSpacing = 20;
    mediaView.interitemSpacing = 20;
    mediaView.allowMultipleSelection = NO;
    mediaView.sectionInset = UIEdgeInsetsMake(20, 20, 20, 20);
    _mediaView = mediaView;
    [mediaView observeViewHeight:^(CGFloat mediaHeight) {
//        self->_mediaH = mediaHeight;
        
        weakSelf.scrollView.contentSize = CGSizeMake(DEWScreenWidth, bottomView.Wbotoom+mediaHeight);
        
    }];
    
    [mediaView observeSelectedMediaArray:^(NSArray<ACMediaModel *> *list) {
        
        weakSelf.photos = [list mutableCopy];
    }];
    
    [self.scrollView addSubview:mediaView];
    
}


-(NSMutableArray *)photos
{
    if (!_photos) {
        _photos = [NSMutableArray array];
    }
    return _photos;
}


- (void)textfieldTextDidChange:(UITextField *)textField
{
    [self sendBtnIsAbleEdit];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
